package org.thinkin.springboot;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thinkin.springboot.compiler.DynamicCompiler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@SpringBootApplication
public class SimpleServerBoot {

    public static void main(String[] args) {
        SpringApplication.run(SimpleServerBoot.class,args);
    }
    @RequestMapping("/")
    public String demo1() {
        return "Hello World";
    }
    @RequestMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        Resource resource = new ClassPathResource("test.xlsx");
        int len = Integer.parseInt(String.valueOf(resource.contentLength()));
        byte[] buff = new byte[len];
        IOUtils.readFully(resource.getInputStream(),buff);
        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition","attachment; filename=test.xlsx");
        response.setContentLength(len);
        response.getOutputStream().write(buff);
    }

    @GetMapping("/debugger/run")
    public String compiler(String importCode,String javaCode) throws Exception {
        DynamicCompiler.compilerAndRun(importCode,javaCode);
        return "OK";
    }
}
